package com.pureut.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.domain.*;
import com.pureut.system.domain.dto.DropListDto;
import com.pureut.system.domain.dto.SampleRequestDetailDto;
import com.pureut.system.domain.dto.SampleRequestInitDto;
import com.pureut.system.domain.dto.SampleRequestPagesDto;
import com.pureut.system.domain.vo.MaterialCertificationApplicationVo;
import com.pureut.system.domain.vo.SampleRequestVo;
import com.pureut.system.mapper.MaterialCodingMapper;
import com.pureut.system.mapper.SampleRequestMapper;
import com.pureut.system.service.IMaterialAwmateriaService;
import com.pureut.system.service.ISampleRequestService;
import com.pureut.system.service.ISampleRequirementService;
import com.pureut.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author: pureut
 * @Date: 2024-12-04 15:44:26
 * @Desc: 样品申请
 */
@Service("sampleRequestService")
public class SampleRequestServiceImpl extends ServiceImpl<SampleRequestMapper, SampleRequest> implements ISampleRequestService {

    /**
     * 样品申请Dao
     */
    @Resource
    private SampleRequestMapper sampleRequestMapper;

    @Resource
    private IMaterialAwmateriaService materialAwmateriaService;

    @Resource
    private ISysDictTypeService dictTypeService;

    /**
     * 样品需求
     */
    @Resource
    private ISampleRequirementService sampleRequirementService;


    @Resource
    FeignService feignService;

    /**
     * 查询列表
     *
     * @param sampleRequestVo
     * @return
     */
    @Override
    public List<SampleRequestPagesDto> queryPage(SampleRequestVo sampleRequestVo) {
        // 获取交接方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("sys_handover_method");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SampleRequestPagesDto> sampleRequestPagesDtos = sampleRequestMapper.selectByPage(sampleRequestVo);
        sampleRequestPagesDtos.forEach(e->{
            e.setApplicationType(netMap.get(String.valueOf(e.getApplicationType())));

        });

        return sampleRequestPagesDtos;

    }


    /**
     * 新增样品申请
     *
     * @param sampleRequestVo
     * @return
     */
    @Transactional
    @Override
    public Boolean save(SampleRequestVo sampleRequestVo) {
        sampleRequestVo.setProposerBy(null);
        SampleRequest sampleRequest = new SampleRequest();
        BeanUtil.copyProperties(sampleRequestVo, sampleRequest);
        sampleRequest.setCreateBy(SecurityUtils.getUsername());
        sampleRequest.setCreateTime(new Date());
        sampleRequest.setProposerBy(SecurityUtils.getUserId());
        boolean save = save(sampleRequest);
        if (save) {
            if (ObjectUtil.isNotEmpty(sampleRequestVo.getSampleRequirementList())) {
                List<SampleRequirement> collect = sampleRequestVo.getSampleRequirementList().stream().map(e -> {
                    SampleRequirement sampleRequirement = new SampleRequirement();
                    sampleRequirement.setCreateBy(SecurityUtils.getUsername());
                    sampleRequirement.setCreateTime(new Date());
                    sampleRequirement.setSampleRequestId(sampleRequest.getId());
                    sampleRequirement.setTechnicalRequirement(e.getTechnicalRequirement());
                    sampleRequirement.setDesignatedSupplier(e.getDesignatedSupplier());
                    sampleRequirement.setMaterialId(e.getMaterialId());
                    return sampleRequirement;
                }).collect(Collectors.toList());
                sampleRequirementService.saveBatch(collect);
            }
        }
        return save;
    }


    /**
     * 更新样品申请
     *
     * @param sampleRequestVo
     * @return
     */
    @Transactional
    @Override
    public Boolean updateById(SampleRequestVo sampleRequestVo) {
        SampleRequest sampleRequest = new SampleRequest();
        BeanUtil.copyProperties(sampleRequestVo, sampleRequest);
        sampleRequest.setUpdateBy(SecurityUtils.getUsername());
        sampleRequest.setUpdateTime(new Date());
        boolean b = updateById(sampleRequest);
        if(b){
            Map<String,Object> map=new HashMap<>();
            map.put("sample_request_id",sampleRequestVo.getId());
            sampleRequirementService.removeByMap(map);
            if (ObjectUtil.isNotEmpty(sampleRequestVo.getSampleRequirementList())) {
                List<SampleRequirement> collect = sampleRequestVo.getSampleRequirementList().stream().map(e -> {
                    SampleRequirement sampleRequirement = new SampleRequirement();
                    sampleRequirement.setCreateBy(SecurityUtils.getUsername());
                    sampleRequirement.setCreateTime(new Date());
                    sampleRequirement.setSampleRequestId(sampleRequest.getId());
                    sampleRequirement.setTechnicalRequirement(e.getTechnicalRequirement());
                    sampleRequirement.setDesignatedSupplier(e.getDesignatedSupplier());
                    sampleRequirement.setMaterialId(e.getMaterialId());
                    return sampleRequirement;
                }).collect(Collectors.toList());
                sampleRequirementService.saveBatch(collect);
            }
        }
        return b;
    }

    /**
     * 获取样品申请 初始化信息
     *
     * @return
     */
    @Override
    public SampleRequestInitDto infoInit() {
        SampleRequestInitDto sampleRequestInitDto = new SampleRequestInitDto();
        String sn = feignService.getAuthorityCoding("warehouse:outbound:reworksto:list");
        if (sn == null) {
            throw new GlobalException("该单据未进行配置,无法生成单据编码");
        }
        sampleRequestInitDto.setDocNum(sn);
        sampleRequestInitDto.setMaterialClassificationList(materialAwmateriaService.selectChildrenListThe2());
        sampleRequestInitDto.setProposerBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        sampleRequestInitDto.setStatus("1");
        sampleRequestInitDto.setApplicationDate(new Date());
        List<SysDictData> data = dictTypeService.selectDictDataByType("sample_status2");
        if (StringUtils.isNull(data)) {
            sampleRequestInitDto.setStatusList(new ArrayList<DropListDto>());
        } else {
            List<DropListDto> dropListDtoStream = data.stream().map(e -> {
                DropListDto dropListDto = new DropListDto();
                dropListDto.setDictValue(e.getDictValue());
                dropListDto.setDictLabel(e.getDictLabel());
                dropListDto.setDictSort(e.getDictSort());
                return dropListDto;
            }).collect(Collectors.toList());
            sampleRequestInitDto.setStatusList(dropListDtoStream);
        }
        return sampleRequestInitDto;
    }

    /**
     * 获取样品申请详细信息
     * @param id
     * @return
     */
    @Override
    public SampleRequestDetailDto getInfoById(Long id){
        SampleRequestDetailDto sampleRequestDetailDto=new SampleRequestDetailDto();
        BeanUtil.copyProperties(getById(id), sampleRequestDetailDto);
        List<SysDictData> data = dictTypeService.selectDictDataByType("sample_status2");
        if (StringUtils.isNull(data)) {
            sampleRequestDetailDto.setStatusList(new ArrayList<DropListDto>());
        } else {
            List<DropListDto> dropListDtoStream = data.stream().map(e -> {
                DropListDto dropListDto = new DropListDto();
                dropListDto.setDictValue(e.getDictValue());
                dropListDto.setDictLabel(e.getDictLabel());
                dropListDto.setDictSort(e.getDictSort());
                return dropListDto;
            }).collect(Collectors.toList());
            sampleRequestDetailDto.setStatusList(dropListDtoStream);
        }
        sampleRequestDetailDto.setMaterialClassificationList(materialAwmateriaService.selectChildrenListThe());
        sampleRequestDetailDto.setSampleRequirementList(sampleRequirementService.getListBySamlpleId(id));
        return sampleRequestDetailDto;
    }

    @Override
   public Boolean examine(MaterialCertificationApplicationVo materialCertificationApplicationVo){
        SampleRequest sampleRequest = new SampleRequest();
        sampleRequest.setId(materialCertificationApplicationVo.getId());
        if(materialCertificationApplicationVo.getAuditState()==1){
            sampleRequest.setStatus("3");
        }else{
            sampleRequest.setStatus("4");
        }
        boolean b = updateById(sampleRequest);

        return b;
    }
}
